package io.renren.config;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.sql.DataSource;
import javax.validation.constraints.NotNull;

import org.apache.commons.io.FileUtils;
import org.hibernate.validator.constraints.NotBlank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.util.ResourceUtils;
import org.springframework.validation.annotation.Validated;

/**
 * 定时任务配置
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-04-20 23:38
 */
@Configuration
@AutoConfigureAfter(DruidConfig.class)
@Validated
public class ScheduleConfig {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	// 数据源
	@Autowired
	@NotNull(message = "数据源不能为空")
	private DataSource dataSource;

	// quartz数据文件位置
	@Value("${spring.quartz.quartzProperties.location}")
	@NotBlank(message = "spring.quartz.quartzProperties.location不能为空")
	private String quartzPropertiesLocation;

	// 延时启动
	@Value("${spring.quartz.startupDelay}")
	private int startupDelay;

	// 可选，QuartzScheduler
	// 启动时更新己存在的Job，这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了
	@Value("${spring.quartz.overwriteExistingJobs}")
	private boolean overwriteExistingJobs;

	// 设置自动启动 默认为true
	@Value("${spring.quartz.autoStartup:true}")
	private boolean autoStartup;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        try {
			File file = ResourceUtils.getFile(quartzPropertiesLocation);
			Properties propertie = new Properties();
			propertie.load(FileUtils.openInputStream(file));
			
			String applicationContextSchedulerContextKey = "applicationContextKey";
			factory.setDataSource(dataSource);
			factory.setQuartzProperties(propertie);
			factory.setSchedulerName(propertie.getProperty("org.quartz.scheduler.instanceName"));
			factory.setStartupDelay(startupDelay);
			factory.setApplicationContextSchedulerContextKey(applicationContextSchedulerContextKey);
			factory.setOverwriteExistingJobs(overwriteExistingJobs);
			factory.setAutoStartup(autoStartup);
			
		} catch (FileNotFoundException e) {
			logger.error("找不到quart配置文件：{}", quartzPropertiesLocation);
			logger.error(e.getMessage());
		} catch (IOException e) {
			logger.error("加载quart配置文件：{}出错", quartzPropertiesLocation);
			logger.error(e.getMessage());
		}
        
        return factory;
    }
}
